
import json
import os

# 读取 JSON 文件
def read_json(file_path):
    with open(file_path, 'r') as f:
        data = json.load(f)
    return data

def points_to_bbox(points):
    x_coords = [p[0] for p in points]
    y_coords = [p[1] for p in points]
    x_min = min(x_coords)
    y_min = min(y_coords)
    x_max = max(x_coords)
    y_max = max(y_coords)
    return x_min, y_min, x_max, y_max

def save_bboxes_to_txt(bboxes, output_path):
    with open(output_path, 'w') as f:
        for bbox in bboxes:
            class_id, x_min, y_min, x_max, y_max = bbox
            f.write(f"{class_id} {x_min} {y_min} {x_max} {y_max}\n")

def process_json_to_txt(json_path, output_txt_path, class_id=0):
    # 1. 读取 JSON 文件
    data = read_json(json_path)

    bboxes = []
    for obj in data["shapes"]:  # 根据 JSON 文件的具体结构调整
        points = obj["points"]  # 获取分割的多边形点
        bbox = points_to_bbox(points)  # 生成包围框
        bboxes.append((class_id, *bbox))  # 添加类别和框信息

    # 2. 保存到 TXT 文件
    save_bboxes_to_txt(bboxes, output_txt_path)
    print(f"Bboxes saved to {output_txt_path}")
def list_json_files(folder_path):
    """
    遍历指定文件夹下的所有 JSON 文件。

    :param folder_path: 文件夹路径
    :return: JSON 文件的完整路径列表
    """
    json_files = []
    # 遍历文件夹及子文件夹
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            # 检查文件扩展名是否为 .json
            if file.endswith('.json'):
                json_files.append(os.path.join(root, file))
    return json_files




json_floder = "/home/yjh_test/test_json/sxhsz-mngbj-2024111401/"
save_txt_floder = "/home/yjh_test/test_json/retult_txt/"

# 获取路径下所有的json文件路径
json_files = list_json_files(json_floder)
for json_file in json_files:
    file_name_with_ext = os.path.basename(json_file)
    file_name = os.path.splitext(file_name_with_ext)[0] + ".txt"
    output_txt = os.path.join(save_txt_floder, file_name)
    # print(output_txt)
    process_json_to_txt(json_file, output_txt)
